package com.atguigu.tingshu.search.consumer;

import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 监听专辑上下架消息的消费者
 *
 * @author Taeyang
 * @date 2025/4/28
 */
@Component
@Log4j2
public class AlbumSearchConsumer {

    private final ItemService itemService;

    public AlbumSearchConsumer(ItemService itemService) {
        this.itemService = itemService;
    }

    /**
     * 专辑上架同步
     *
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "search_upper_queue")
    public void albumUpperSearch(Channel channel, Message message) {
        String s = new String(message.getBody());
        // 获取消息
        Long albumId = Long.valueOf(s);
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 执行上架业务
            itemService.albumFromMysqlToEs(albumId);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 异常捕获，再来一次
            if (messageProperties.getRedelivered()) {
                log.error("专辑上架操作失败，专辑的id为：" + albumId + "，失败原因是：" + e.getMessage());
                // 两次都失败，记录到日志 - redis-mysql -- 补偿机制
                channel.basicReject(deliveryTag, false);
            } else {
                channel.basicReject(deliveryTag, true);
            }
        }
    }

    /**
     * 专辑下架同步
     *
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "search_down_queue")
    public void albumDownSearch(Channel channel, Message message) {
        String s = new String(message.getBody());
        // 获取消息
        Long albumId = Long.valueOf(s);
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 执行下架业务
            itemService.removeAlbumFromEs(albumId);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 异常捕获，再来一次
            if (messageProperties.getRedelivered()) {
                log.error("专辑下架操作失败，专辑的id为：" + albumId + "，失败原因是：" + e.getMessage());
                // 两次都失败，记录到日志 - redis-mysql -- 补偿机制
                channel.basicReject(deliveryTag, false);
            } else {
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
